package com.hontech.kaltaapp.utils

private val HEX_LIST = arrayOf(
    '0', '1', '2', '3',
    '4', '5', '6', '7',
    '8', '9', 'A', 'B',
    'C', 'D', 'E', 'F'
)


fun Byte.toU8() = this.toInt() and 0xFF

fun Byte.toLU8() = this.toLong() and 0xFF

fun xorSum(buf: ByteArray, index: Int, len: Int): Int {
    var value = 0
    for (i in index until (index + len)) {
        value = value xor buf[i].toU8()
    }
    return value
}

fun Int.isBitSet(offset: Int) = (this and (0x01 shl offset)) != 0

fun Byte.toHex(): String {
    val v = this.toU8()
    val h = v / 16
    val l = v % 16
    return "${HEX_LIST[h]}${HEX_LIST[l]}"
}

fun ByteArray.toHexs(): String {
    val sb = StringBuilder()
    for (v in this) {
        sb.append(v.toHex())
        sb.append(" ")
    }
    return sb.toString()
}

fun Int.toHex4(): String {
    val h0 = (this shr 12) and 0x0F
    val h1 = (this shr 8) and 0x0F
    val h2 = (this shr 4) and 0x0F
    val h3 = this and 0x0F
    return "${HEX_LIST[h0]}${HEX_LIST[h1]}${HEX_LIST[h2]}${HEX_LIST[h3]}"
}



